import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_oldman_health/api/album_service.dart';
import 'package:flutter_oldman_health/api/constant.dart';
import 'package:flutter_oldman_health/models/album_data_model.dart';
import 'package:flutter_oldman_health/models/response_data_model.dart';
import 'package:flutter_oldman_health/utils/utils.dart';

class AlbumItemDeletePage extends StatefulWidget {
  List<AlbumModel> myAlbumList;

  AlbumItemDeletePage(this.myAlbumList);

  @override
  AlbumItemDeletePageState createState() {
    return AlbumItemDeletePageState();
  }
}

class AlbumItemDeletePageState extends State<AlbumItemDeletePage> {
  Size screenSize;

  bool isLoadingData = false;
  bool change = false;
  int selectAlbumNum = 0;

  String albumName, newAlbumId;
  List<AlbumModel> checkedAlbumList = [];

  AlbumItemDeletePageState();

  @override
  Widget build(BuildContext context) {
    screenSize = MediaQuery.of(context).size;

    return Scaffold(
        resizeToAvoidBottomInset: true,
        //重点 监听返回键
        body: WillPopScope(
            onWillPop: () async {
              Navigator.pop(context, change);
              return false;
            },
            child: Container(
                color: Constant.backgroundColor,
                child: Column(children: [
                  _getTitle(),
                  Stack(children: [
                    Container(
                        width: screenSize.width - 24,
                        height: screenSize.height - 100,
                        child: MediaQuery.removePadding(
                            context: context,
                            removeTop: true,
                            child: GridView(
                                gridDelegate:
                                    SliverGridDelegateWithFixedCrossAxisCount(
                                  childAspectRatio: 0.76,
                                  crossAxisCount: 2,
                                  mainAxisSpacing: 4,
                                  crossAxisSpacing: 4,
                                ),
                                children: _getListData())))
                  ])
                ]))));
  }

  void deleteAlbum(AlbumModel album) {
    setState(() {
      isLoadingData = true;
    });
    AlbumService.deleteAlbum(album.id).then((value) {
      setState(() {
        isLoadingData = false;
      });
      if (value != null && value.statusCode == 200) {
        ResponseDataModel<String> response =
            ResponseDataModel.fromJson(value.data);
        if (response != null && response.success() && response.data != null) {
          change = true;
          setState(() {
            if (selectAlbumNum > 0)--selectAlbumNum;
            widget.myAlbumList.remove(album);
          });
          if (widget.myAlbumList.isEmpty) {
            Navigator.pop(context, change);
          }
          // EasyLoading.showSuccess(response.msg);
        } else {
          EasyLoading.showInfo(response.msg);
        }
      }
    });
  }

  Widget assetImage() {
    return Image.asset('images/ic_album.png',
        width: double.maxFinite,
        height: screenSize.width / 2 - 20,
        fit: BoxFit.cover);
  }

  Widget getImageWidget(bool check, String imgUrl) {
    return Card(
        shape: RoundedRectangleBorder(
            borderRadius: BorderRadiusDirectional.circular(8)),
        clipBehavior: Clip.antiAlias,
        child: Stack(alignment: Alignment.bottomCenter, children: [
          imgUrl != null
              ? CachedNetworkImage(
                  width: double.maxFinite,
                  height: screenSize.width / 2 - 20,
                  fit: BoxFit.cover,
                  imageUrl: imgUrl,
                  placeholder: (context, url) => assetImage(),
                      // CommonContainer.loadingView(h: 50),
                  errorWidget: (context, url, error) => assetImage(),
                )
              : assetImage(),
          if (check)
            Container(
                height: 30,
                width: double.maxFinite,
                color: Colors.orange,
                child: Icon(Icons.check_sharp, size: 25, color: Colors.white))
        ]));
  }

  List<Widget> _getListData() {
    var tempList = widget.myAlbumList.map((e) => GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: () {
          setState(() {
            if (!checkedAlbumList.contains(e)) {
              print(selectAlbumNum);

              selectAlbumNum = selectAlbumNum + 1;
              checkedAlbumList.add(e);
              print(selectAlbumNum);
            } else {
              if (selectAlbumNum > 0) --selectAlbumNum;
              checkedAlbumList.remove(e);
            }
          });
        },
        child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
          getImageWidget(
              checkedAlbumList.contains(e),
              (e.photos != null && e.photos.length > 0)
                  ? e.photos[0].location
                  : null),
          Padding(
              padding: EdgeInsets.only(left: 10),
              child: Text(e.name, maxLines: 1, style: TextStyle(fontSize: 17))),
          Padding(
              padding: EdgeInsets.only(left: 10),
              child: Text("创建人：${e.creator}",
                  maxLines: 1,
                  style: TextStyle(fontSize: 12, color: Color(0xaa333333))))
        ])));
    return tempList.toList();
  }

  Widget _getTitle([String title = "相册"]) {
    return Container(
        color: Constant.appbarColor,
        padding: EdgeInsets.fromLTRB(16, 46, 16, 16),
        child: FractionallySizedBox(
          widthFactor: 1,
          child: Stack(
            alignment: Alignment.center,
            children: [
              Positioned(
                left: 2,
                child: GestureDetector(
                  behavior: HitTestBehavior.translucent,
                  onTap: () {
                    Navigator.pop(context, change);
                  },
                  child: Container(
                      child: Icon(Icons.arrow_back_ios),
                      padding: EdgeInsets.fromLTRB(15, 10, 20, 10)),
                ),
              ),
              Text(title,
                  textAlign: TextAlign.center,
                  style: TextStyle(
                      fontSize: 22,
                      color: Colors.black87,
                      fontWeight: FontWeight.normal)),
              Positioned(
                  right: 2,
                  child: GestureDetector(
                      behavior: HitTestBehavior.translucent,
                      onTap: () {
                        if (selectAlbumNum > 0) {
                          showRemindDialog(context);
                        } else {
                          EasyLoading.showInfo("请先选中要删除的相册");
                        }
                      },
                      child: Text("删除", style: TextStyle(fontSize: 18))))
            ],
          ),
        ));
  }

  Future showRemindDialog(BuildContext context) async {
    var result = await showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
              title: Text("您确定要删除整个相册？", style: TextStyle(fontSize: 17)),
              content:
                  Text("删除相册后,相册内的所有照片也将被删除", style: TextStyle(fontSize: 17)),
              actions: <Widget>[
                ElevatedButton(
                    onPressed: () {
                      Navigator.pop(context);
                    },
                    child: Padding(
                        padding: EdgeInsets.fromLTRB(12, 8, 12, 8),
                        child: Text("取消")),
                    style: ButtonStyle(
                      shape: MaterialStateProperty.all(StadiumBorder(
                          side: BorderSide(
                              //设置 界面效果 圆角弧度
                              style: BorderStyle.solid,
                              color: Colors.grey[400]))),
                      foregroundColor:
                          MaterialStateProperty.all(Color(0xff333333)),
                      backgroundColor: MaterialStateProperty.all(Colors.white),
                      textStyle:
                          MaterialStateProperty.all(TextStyle(fontSize: 17)),
                    )),
                ElevatedButton(
                    onPressed: () async {
                      checkedAlbumList.forEach((element) {
                        deleteAlbum(element);
                      });
                      Navigator.pop(context);
                    },
                    child: Padding(
                        padding: EdgeInsets.fromLTRB(12, 8, 12, 8),
                        child: Text("确定")),
                    style: ButtonStyle(
                        backgroundColor:
                            MaterialStateProperty.all(Colors.orange),
                        textStyle:
                            MaterialStateProperty.all(TextStyle(fontSize: 17)),
                        shape: MaterialStateProperty.all(StadiumBorder(
                            side: BorderSide(
                          //设置 界面效果 圆角弧度
                          style: BorderStyle.solid,
                          color: Color(0xffFF7F24),
                        ))))),
              ]);
        });
    return result;
  }
}
